﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Contracts;
using System.ServiceModel;

namespace Services
{
    /// <summary>
    /// 服务的实现
    /// Tips：
    /// 实现发布订阅,要注意：每个信道在调用后不要回收，否则会在回调时报错
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults = false)]
    public partial class ServiceImp : ICalculator
    {
        public string Add(string js)
        {
            try
            {
                IPushCallback callbackChannel = OperationContext.Current.GetCallbackChannel<IPushCallback>();
                //添加到管理列表中
                string result = CalculatorBaseService.GetInstance().Add(js);
                //callbackChannel.NotifyMessage(result);
                string SessionId = OperationContext.Current.SessionId;
                ChannelManager.Instance.Add(SessionId, callbackChannel);

                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public double Subtract(double x, double y)
        {
            return x - y;
        }

        public double Multiply(double x, double y)
        {
            return x * y;
        }

        public double Divide(double x, double y)
        {
            return x / y;
        }

        public void UnRegist()
        {
            IPushCallback callbackChannel = OperationContext.Current.GetCallbackChannel<IPushCallback>();
            //从管理列表中移除
            string SessionId = OperationContext.Current.SessionId;
            ChannelManager.Instance.Remove(SessionId, callbackChannel);
        }
    }
}